<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Glide,">










<meta name="description" content="序言 本篇文章聊的是Glide的缓存策略，首先需要对加载流程有一定的了解，如果还没看过Glide加载流程的，建议先看完我的上一篇文章。  这篇文章还是关于源码的文章，但同样不会涉及到Glide的使用方法  与上篇文章一样，同样基于Glide:4.8.0  只对最基本的Glide.with().load().into()进行分析">
<meta name="keywords" content="Glide">
<meta property="og:type" content="article">
<meta property="og:title" content="Glide(2)-基于Glide4.8的缓存原理分析">
<meta property="og:url" content="https://lt19931203.github.io/2019/02/21/Glide(2)-基于Glide4.8的缓存原理分析/index.html">
<meta property="og:site_name" content="LiuTao">
<meta property="og:description" content="序言 本篇文章聊的是Glide的缓存策略，首先需要对加载流程有一定的了解，如果还没看过Glide加载流程的，建议先看完我的上一篇文章。  这篇文章还是关于源码的文章，但同样不会涉及到Glide的使用方法  与上篇文章一样，同样基于Glide:4.8.0  只对最基本的Glide.with().load().into()进行分析">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-02-21T12:58:53.570Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Glide(2)-基于Glide4.8的缓存原理分析">
<meta name="twitter:description" content="序言 本篇文章聊的是Glide的缓存策略，首先需要对加载流程有一定的了解，如果还没看过Glide加载流程的，建议先看完我的上一篇文章。  这篇文章还是关于源码的文章，但同样不会涉及到Glide的使用方法  与上篇文章一样，同样基于Glide:4.8.0  只对最基本的Glide.with().load().into()进行分析">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://lt19931203.github.io/2019/02/21/Glide(2)-基于Glide4.8的缓存原理分析/">





  <title>Glide(2)-基于Glide4.8的缓存原理分析 | LiuTao</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">LiuTao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Android开发者</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://lt19931203.github.io/2019/02/21/Glide(2)-基于Glide4.8的缓存原理分析/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="lt19931203">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LiuTao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Glide(2)-基于Glide4.8的缓存原理分析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-02-21T20:48:06+08:00">
                2019-02-21
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2019/02/21/Glide(2)-基于Glide4.8的缓存原理分析/" class="leancloud_visitors" data-flag-title="Glide(2)-基于Glide4.8的缓存原理分析">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  6.8k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="序言"><a href="#序言" class="headerlink" title="序言"></a>序言</h1><ol>
<li><p>本篇文章聊的是<code>Glide</code>的缓存策略，首先需要对加载流程有一定的了解，如果还没看过<code>Glide</code>加载流程的，建议先看完我的上一篇文章。</p>
</li>
<li><p>这篇文章还是关于源码的文章，但同样不会涉及到<code>Glide</code>的使用方法</p>
</li>
<li><p>与上篇文章一样，同样基于<code>Glide:4.8.0</code></p>
</li>
<li><p>只对最基本的<code>Glide.with().load().into()</code>进行分析</p>
<a id="more"></a>
</li>
</ol>
<h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><p>所有用过<code>Glide</code>的朋友都知道，<code>Glide</code>缓存嘛，无非就是分为两部分，内存和磁盘。通过一些API跳过内存缓存，或者改变磁盘缓存的策略，都是老生常谈的东西了，网上的文章也是数不胜数，不过我个人还是喜欢按步骤来拆分源码的。话不多说，直接来看代码。</p>
<h1 id="内存缓存"><a href="#内存缓存" class="headerlink" title="内存缓存"></a>内存缓存</h1><p><strong>Glide的内存缓存不止一层，而是两层，分别是ActiveResources（表示当前内存中正在使用的，优先级高）和LruCache（最近最少使用算法，优先级低于ActiveResources）</strong>，如果有对<code>LruCache</code>算法不了解的，可以在网上搜索了解一下，这里就不介绍了。在上一篇文章中说到了<code>Glide</code>首次加载流程，其中<code>Glide.with().load()</code>这两步都没有做太多的事情，大部分的逻辑都是在<code>into()</code>方法中完成的，我们还认识了一些类，包括他们的方法，做了哪些事…，这篇文章不从头来了，直接从<code>Engine#load()</code>方法开始。因为在<code>Engine#load()</code>之前做的事情，都和缓存关系不大。如果有小伙伴对于<code>Engine#load()</code>来源不清楚的，建议还是先看首次加载流程吧。</p>
<h2 id="步骤1：Engine-load"><a href="#步骤1：Engine-load" class="headerlink" title="步骤1：Engine#load()"></a>步骤1：Engine#load()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line">public &lt;R&gt; LoadStatus load(</span><br><span class="line">        GlideContext glideContext,</span><br><span class="line">        Object model,</span><br><span class="line">        Key signature,</span><br><span class="line">        int width,</span><br><span class="line">        int height,</span><br><span class="line">        Class&lt;?&gt; resourceClass,</span><br><span class="line">        Class&lt;R&gt; transcodeClass,</span><br><span class="line">        Priority priority,</span><br><span class="line">        DiskCacheStrategy diskCacheStrategy,</span><br><span class="line">        Map&lt;Class&lt;?&gt;, Transformation&lt;?&gt;&gt; transformations,</span><br><span class="line">        boolean isTransformationRequired,</span><br><span class="line">        boolean isScaleOnlyOrNoTransform,</span><br><span class="line">        Options options,</span><br><span class="line">        boolean isMemoryCacheable,</span><br><span class="line">        boolean useUnlimitedSourceExecutorPool,</span><br><span class="line">        boolean useAnimationPool,</span><br><span class="line">        boolean onlyRetrieveFromCache,</span><br><span class="line">        ResourceCallback cb) &#123;</span><br><span class="line">    Util.assertMainThread();</span><br><span class="line">    long startTime = VERBOSE_IS_LOGGABLE ? LogTime.getLogTime() : 0;</span><br><span class="line">    EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,</span><br><span class="line">            resourceClass, transcodeClass, options);</span><br><span class="line">    EngineResource&lt;?&gt; active = loadFromActiveResources(key, isMemoryCacheable);</span><br><span class="line">    if (active != null) &#123;</span><br><span class="line">        cb.onResourceReady(active, DataSource.MEMORY_CACHE);</span><br><span class="line">        if (VERBOSE_IS_LOGGABLE) &#123;</span><br><span class="line">            logWithTimeAndKey(&quot;Loaded resource from active resources&quot;, startTime, key);</span><br><span class="line">        &#125;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">    EngineResource&lt;?&gt; cached = loadFromCache(key, isMemoryCacheable);</span><br><span class="line">    if (cached != null) &#123;</span><br><span class="line">        cb.onResourceReady(cached, DataSource.MEMORY_CACHE);</span><br><span class="line">        if (VERBOSE_IS_LOGGABLE) &#123;</span><br><span class="line">            logWithTimeAndKey(&quot;Loaded resource from cache&quot;, startTime, key);</span><br><span class="line">        &#125;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">    EngineJob&lt;?&gt; current = jobs.get(key, onlyRetrieveFromCache);</span><br><span class="line">    if (current != null) &#123;</span><br><span class="line">        current.addCallback(cb);</span><br><span class="line">        if (VERBOSE_IS_LOGGABLE) &#123;</span><br><span class="line">            logWithTimeAndKey(&quot;Added to existing load&quot;, startTime, key);</span><br><span class="line">        &#125;</span><br><span class="line">        return new LoadStatus(cb, current);</span><br><span class="line">    &#125;</span><br><span class="line">    EngineJob&lt;R&gt; engineJob =</span><br><span class="line">            engineJobFactory.build(</span><br><span class="line">                    key,</span><br><span class="line">                    isMemoryCacheable,</span><br><span class="line">                    useUnlimitedSourceExecutorPool,</span><br><span class="line">                    useAnimationPool,</span><br><span class="line">                    onlyRetrieveFromCache);</span><br><span class="line">    DecodeJob&lt;R&gt; decodeJob =</span><br><span class="line">            decodeJobFactory.build(</span><br><span class="line">                    glideContext,</span><br><span class="line">                    model,</span><br><span class="line">                    key,</span><br><span class="line">                    signature,</span><br><span class="line">                    width,</span><br><span class="line">                    height,</span><br><span class="line">                    resourceClass,</span><br><span class="line">                    transcodeClass,</span><br><span class="line">                    priority,</span><br><span class="line">                    diskCacheStrategy,</span><br><span class="line">                    transformations,</span><br><span class="line">                    isTransformationRequired,</span><br><span class="line">                    isScaleOnlyOrNoTransform,</span><br><span class="line">                    onlyRetrieveFromCache,</span><br><span class="line">                    options,</span><br><span class="line">                    engineJob);</span><br><span class="line"></span><br><span class="line">    jobs.put(key, engineJob);</span><br><span class="line">    engineJob.addCallback(cb);</span><br><span class="line">    engineJob.start(decodeJob);</span><br><span class="line">    if (VERBOSE_IS_LOGGABLE) &#123;</span><br><span class="line">        logWithTimeAndKey(&quot;Started new load&quot;, startTime, key);</span><br><span class="line">    &#125;</span><br><span class="line">    return new LoadStatus(cb, engineJob);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>开始分析，目光放在第22行，<code>keyFactory.buildKey()</code>方法，传入了一大批参数，看名字就知道了，这是用来生成缓存的key的，可见这个key由太多因素决定了，最终返回结果是<code>EngineKey</code>对象，其实也是封装了一下，把多个参数合并了一个<code>EngineKey</code>。接着看第24行，<code>loadFromActiveResources();</code>这个方法看名称就知道是从<code>ActiveResources</code>中拿数据，也就是第一层内存缓存</p>
<h2 id="步骤2：Engine-loadFromActiveResources"><a href="#步骤2：Engine-loadFromActiveResources" class="headerlink" title="步骤2：Engine#loadFromActiveResources()"></a>步骤2：Engine#loadFromActiveResources()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">private EngineResource&lt;?&gt; loadFromActiveResources(Key key, boolean isMemoryCacheable) &#123;</span><br><span class="line">    if (!isMemoryCacheable) &#123;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">    EngineResource&lt;?&gt; active = activeResources.get(key);</span><br><span class="line">    if (active != null) &#123;</span><br><span class="line">        active.acquire();</span><br><span class="line">    &#125;</span><br><span class="line">    return active;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li><p>第2行，判断内存缓存是否启用了，Glide默认启用的，我们没有设置其他API，所以条件不成立，继续往下走</p>
</li>
<li><p>第5行，<code>activeResources.get()</code>方法，这个<code>activeResources</code>是一个<code>ActiveResources</code>对象，看起来不是一个Map，实际上在<code>ActiveResources</code>的内部封装了一个<code>Map</code>，用来进行内存缓存。代码就不贴了，等用到的时候再看。到这里就直接返回结果了</p>
</li>
<li><p>第6和第7行，如果<code>active</code>不是<code>null</code>，那么调用<code>active.acquire()</code>方法。这里我们假设是有内存缓存的，继续往下这个<code>acquire()</code>方法做了什么呢？</p>
<p><code>EngineResource#acquire()</code>和<code>release()</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">void acquire() &#123;</span><br><span class="line">    if (isRecycled) &#123;</span><br><span class="line">        throw new IllegalStateException(&quot;Cannot acquire a recycled resource&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    if (!Looper.getMainLooper().equals(Looper.myLooper())) &#123;</span><br><span class="line">        throw new IllegalThreadStateException(&quot;Must call acquire on the main thread&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    ++acquired;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">void release() &#123;</span><br><span class="line">    if (acquired &lt;= 0) &#123;</span><br><span class="line">        throw new IllegalStateException(&quot;Cannot release a recycled or not yet acquired resource&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    if (!Looper.getMainLooper().equals(Looper.myLooper())) &#123;</span><br><span class="line">        throw new IllegalThreadStateException(&quot;Must call release on the main thread&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    if (--acquired == 0) &#123;</span><br><span class="line">        listener.onResourceReleased(key, this);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第8行，<code>++acquired</code>，这个<code>acquired</code>是一个int值，这里就是将引用次数+1；与之对应的就是<code>release()</code>方法， 第18行，<code>--acquired</code>，代表这个<code>Resource</code>引用次数被减少一次。第19行，当<code>acquired == 0</code>的时候回调<code>listener.onResourceReleased()</code>方法，这是用来干嘛的，后面会提到</p>
</li>
</ol>
<h2 id="步骤3：SingleRequest-onResourceReady"><a href="#步骤3：SingleRequest-onResourceReady" class="headerlink" title="步骤3：SingleRequest#onResourceReady()"></a>步骤3：SingleRequest#onResourceReady()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">public void onResourceReady(Resource&lt;?&gt; resource, DataSource dataSource) &#123;</span><br><span class="line">    stateVerifier.throwIfRecycled();</span><br><span class="line">    loadStatus = null;</span><br><span class="line">    if (resource == null) &#123;</span><br><span class="line">        GlideException exception = new GlideException(&quot;Expected to receive a Resource&lt;R&gt; with an &quot;</span><br><span class="line">                + &quot;object of &quot; + transcodeClass + &quot; inside, but instead got null.&quot;);</span><br><span class="line">        onLoadFailed(exception);</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Object received = resource.get();</span><br><span class="line">    if (received == null || !transcodeClass.isAssignableFrom(received.getClass())) &#123;</span><br><span class="line">        releaseResource(resource);</span><br><span class="line">        GlideException exception = new GlideException(&quot;Expected to receive an object of &quot;</span><br><span class="line">                + transcodeClass + &quot; but instead&quot; + &quot; got &quot;</span><br><span class="line">                + (received != null ? received.getClass() : &quot;&quot;) + &quot;&#123;&quot; + received + &quot;&#125; inside&quot; + &quot; &quot;</span><br><span class="line">                + &quot;Resource&#123;&quot; + resource + &quot;&#125;.&quot;</span><br><span class="line">                + (received != null ? &quot;&quot; : &quot; &quot; + &quot;To indicate failure return a null Resource &quot;</span><br><span class="line">                + &quot;object, rather than a Resource object containing null data.&quot;));</span><br><span class="line">        onLoadFailed(exception);</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    if (!canSetResource()) &#123;</span><br><span class="line">        releaseResource(resource);</span><br><span class="line">        // We can&apos;t put the status to complete before asking canSetResource().</span><br><span class="line">        status = SingleRequest.Status.COMPLETE;</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    onResourceReady((Resource&lt;R&gt;) resource, (R) received, dataSource);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//重载方法</span><br><span class="line">private void onResourceReady(Resource&lt;R&gt; resource, R result, DataSource dataSource) &#123;</span><br><span class="line">    // We must call isFirstReadyResource before setting status.</span><br><span class="line">    boolean isFirstResource = isFirstReadyResource();</span><br><span class="line">    status = SingleRequest.Status.COMPLETE;</span><br><span class="line">    this.resource = resource;</span><br><span class="line"></span><br><span class="line">    if (glideContext.getLogLevel() &lt;= Log.DEBUG) &#123;</span><br><span class="line">        Log.d(GLIDE_TAG, &quot;Finished loading &quot; + result.getClass().getSimpleName() + &quot; from &quot;</span><br><span class="line">                + dataSource + &quot; for &quot; + model + &quot; with size [&quot; + width + &quot;x&quot; + height + &quot;] in &quot;</span><br><span class="line">                + LogTime.getElapsedMillis(startTime) + &quot; ms&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    isCallingCallbacks = true;</span><br><span class="line">    try &#123;</span><br><span class="line">        boolean anyListenerHandledUpdatingTarget = false;</span><br><span class="line">        if (requestListeners != null) &#123;</span><br><span class="line">            for (RequestListener&lt;R&gt; listener : requestListeners) &#123;</span><br><span class="line">                anyListenerHandledUpdatingTarget |=</span><br><span class="line">                        listener.onResourceReady(result, model, target, dataSource, isFirstResource);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        anyListenerHandledUpdatingTarget |=</span><br><span class="line">                targetListener != null</span><br><span class="line">                        &amp;&amp; targetListener.onResourceReady(result, model, target, dataSource, isFirstResource);</span><br><span class="line"></span><br><span class="line">        if (!anyListenerHandledUpdatingTarget) &#123;</span><br><span class="line">            Transition&lt;? super R&gt; animation =</span><br><span class="line">                    animationFactory.build(dataSource, isFirstResource);</span><br><span class="line">            target.onResourceReady(result, animation);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; finally &#123;</span><br><span class="line">        isCallingCallbacks = false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    notifyLoadSuccess();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>拿到结果之后，回到步骤1的第26行，<code>cb.onResourceReady()</code>这是一个回调方法，cb对象指向的是<code>SingleRequest</code>，参照上方代码，<code>onResourceReady()</code>有一个重载方法，我们先看第一个方法，第7行，第20行是<code>onLoadFailed()</code>显然不会走，继续来到第31行，进入重载方法，关键代码在第63行，<code>target.onResourceReady()</code>，这个target对象我们也很熟悉了，之前分析过是<code>DrawableImageViewTarget</code>对象，<code>DrawableImageViewTarget</code>中没有<code>onResourceReady()</code>方法来到他的父类<code>ImageViewTarget#onResourceReady()</code>中</p>
<p><strong>ImageViewTarget#onResourceReady()</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public void onResourceReady(@NonNull Z resource, @Nullable Transition&lt;? super Z&gt; transition) &#123;</span><br><span class="line">    if (transition == null || !transition.transition(resource, this)) &#123;</span><br><span class="line">        setResourceInternal(resource);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        maybeUpdateAnimatable(resource);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接着调用<code>setResourceInternal(resource);</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">private void setResourceInternal(@Nullable Z resource) &#123;</span><br><span class="line">    setResource(resource);</span><br><span class="line">    maybeUpdateAnimatable(resource);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>又调用<code>setResource()</code>方法，在<code>ImageViewTarget</code>中<code>setResource()</code>是个抽象方法，我们来到<code>DrawableImageViewTarget</code>类中查看</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">protected void setResource(@Nullable Drawable resource) &#123;</span><br><span class="line">    view.setImageDrawable(resource);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>找到答案了，就跟第一次加载流程一样。内存缓存的获取还是不复杂的，接下来看一下内存缓存是从哪里<code>put()</code>的或者<code>set()</code>的。</p>
<h2 id="步骤4：ActiveResources缓存的来源"><a href="#步骤4：ActiveResources缓存的来源" class="headerlink" title="步骤4：ActiveResources缓存的来源"></a>步骤4：ActiveResources缓存的来源</h2><p>我们首先来看一下步骤2第一段代码第5行，<code>EngineResource&lt;?&gt; active = activeResources.get(key);</code>既然结果是从<code>activeResources</code>的<code>get()</code>方法获取的，那么我们就要了解一下这个类的结构了。</p>
<p><code>ActiveResources</code>类结构如下，只提取了部分关键代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line">final class ActiveResources &#123;</span><br><span class="line">    @VisibleForTesting</span><br><span class="line">    final Map&lt;Key, ResourceWeakReference&gt; activeEngineResources = new HashMap&lt;&gt;();</span><br><span class="line">    ActiveResources(boolean isActiveResourceRetentionAllowed) &#123;</span><br><span class="line">        this.isActiveResourceRetentionAllowed = isActiveResourceRetentionAllowed;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    void setListener(EngineResource.ResourceListener listener) &#123;</span><br><span class="line">        this.listener = listener;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    void activate(Key key, EngineResource&lt;?&gt; resource) &#123;</span><br><span class="line">        ResourceWeakReference toPut =</span><br><span class="line">                new ResourceWeakReference(</span><br><span class="line">                        key,</span><br><span class="line">                        resource,</span><br><span class="line">                        getReferenceQueue(),</span><br><span class="line">                        isActiveResourceRetentionAllowed);</span><br><span class="line">        ResourceWeakReference removed = activeEngineResources.put(key, toPut);</span><br><span class="line">        if (removed != null) &#123;</span><br><span class="line">            removed.reset();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    void deactivate(Key key) &#123;</span><br><span class="line">        ResourceWeakReference removed = activeEngineResources.remove(key);</span><br><span class="line">        if (removed != null) &#123;</span><br><span class="line">            removed.reset();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    @Nullable</span><br><span class="line">    EngineResource&lt;?&gt; get(Key key) &#123;</span><br><span class="line">        ResourceWeakReference activeRef = activeEngineResources.get(key);</span><br><span class="line">        if (activeRef == null) &#123;</span><br><span class="line">            return null;</span><br><span class="line">        &#125;</span><br><span class="line">        EngineResource&lt;?&gt; active = activeRef.get();</span><br><span class="line">        if (active == null) &#123;</span><br><span class="line">            cleanupActiveReference(activeRef);</span><br><span class="line">        &#125;</span><br><span class="line">        return active;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    @VisibleForTesting</span><br><span class="line">    static final class ResourceWeakReference extends WeakReference&lt;EngineResource&lt;?&gt;&gt; &#123;</span><br><span class="line">        @SuppressWarnings(&quot;WeakerAccess&quot;)</span><br><span class="line">        @Synthetic</span><br><span class="line">        final Key key;</span><br><span class="line">        @SuppressWarnings(&quot;WeakerAccess&quot;)</span><br><span class="line">        @Synthetic</span><br><span class="line">        final boolean isCacheable;</span><br><span class="line">        @Nullable</span><br><span class="line">        @SuppressWarnings(&quot;WeakerAccess&quot;)</span><br><span class="line">        @Synthetic</span><br><span class="line">        Resource&lt;?&gt; resource;</span><br><span class="line">        @Synthetic</span><br><span class="line">        @SuppressWarnings(&quot;WeakerAccess&quot;)</span><br><span class="line">        ResourceWeakReference(</span><br><span class="line">                @NonNull Key key,</span><br><span class="line">                @NonNull EngineResource&lt;?&gt; referent,</span><br><span class="line">                @NonNull ReferenceQueue&lt;? super EngineResource&lt;?&gt;&gt; queue,</span><br><span class="line">                boolean isActiveResourceRetentionAllowed) &#123;</span><br><span class="line">            super(referent, queue);</span><br><span class="line">            this.key = Preconditions.checkNotNull(key);</span><br><span class="line">            this.resource =</span><br><span class="line">                    referent.isCacheable() &amp;&amp; isActiveResourceRetentionAllowed</span><br><span class="line">                            ? Preconditions.checkNotNull(referent.getResource()) : null;</span><br><span class="line">            isCacheable = referent.isCacheable();</span><br><span class="line">        &#125;</span><br><span class="line">        void reset() &#123;</span><br><span class="line">            resource = null;</span><br><span class="line">            clear();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>首先锁定<code>get()</code>方法，第34行，<code>activeEngineResources.get(key)</code>，这个<code>activeEngineResources</code>对象是一个Map集合，那我们要找一下<code>put()</code>方法在哪里了，第19行，有个<code>activeEngineResources.put()</code>方法，它被<code>ActiveResources#activate()</code>方法调用，这个<code>activate()</code>方法做的事情很简单，封装了一个<code>ResourceWeakReference</code>来存储<code>Resource</code>对象，而这个<code>ResourceWeakReference</code>对象我们在46行可以看到继承了<code>WeakReference</code>类表明是个弱引用，我们来找一下<code>ActiveResources#activate()</code>方法在哪里被调用就可以了。</p>
<h2 id="步骤5：Engine-onEngineJobComplete"><a href="#步骤5：Engine-onEngineJobComplete" class="headerlink" title="步骤5：Engine#onEngineJobComplete()"></a>步骤5：Engine#onEngineJobComplete()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public void onEngineJobComplete(EngineJob&lt;?&gt; engineJob, Key key, EngineResource&lt;?&gt; resource) &#123;</span><br><span class="line">    Util.assertMainThread();</span><br><span class="line">    if (resource != null) &#123;</span><br><span class="line">        resource.setResourceListener(key, this);</span><br><span class="line">        if (resource.isCacheable()) &#123;</span><br><span class="line">            activeResources.activate(key, resource);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    jobs.removeIfCurrent(key, engineJob);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在第6行，调用了<code>ActiveResources#activate()</code>方法，看起来我们还需要继续找<code>Engine#onEngineJobComplete()</code>是在哪里调用的，不过这个方法很熟悉，似乎在首次加载流程分析的时候看到过，如果回到Glide首次加载流程分析那篇文章就可以知道，在那篇文章的第65步骤，就讲解了这个方法，是在网络加载成功之后回调的，有意向的小伙伴可以回去看一下。这里就不带大家看了。</p>
<h2 id="步骤6：Engine-loadFromCache"><a href="#步骤6：Engine-loadFromCache" class="headerlink" title="步骤6：Engine#loadFromCache()"></a>步骤6：Engine#loadFromCache()</h2><p>接下来我们开始分析<code>LruCache</code>。如果步骤1的第24行没有拿到结果，那么再看步骤1第32行，<code>EngineResource&lt;?&gt; cached = loadFromCache(key, isMemoryCacheable);</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">private EngineResource&lt;?&gt; loadFromCache(Key key, boolean isMemoryCacheable) &#123;</span><br><span class="line">    if (!isMemoryCacheable) &#123;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">    EngineResource&lt;?&gt; cached = getEngineResourceFromCache(key);</span><br><span class="line">    if (cached != null) &#123;</span><br><span class="line">        cached.acquire();</span><br><span class="line">        activeResources.activate(key, cached);</span><br><span class="line">    &#125;</span><br><span class="line">    return cached;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">private EngineResource&lt;?&gt; getEngineResourceFromCache(Key key) &#123;</span><br><span class="line">    Resource&lt;?&gt; cached = cache.remove(key);</span><br><span class="line">    final EngineResource&lt;?&gt; result;</span><br><span class="line">    if (cached == null) &#123;</span><br><span class="line">        result = null;</span><br><span class="line">    &#125; else if (cached instanceof EngineResource) &#123;</span><br><span class="line">        // Save an object allocation if we&apos;ve cached an EngineResource (the typical case).</span><br><span class="line">        result = (EngineResource&lt;?&gt;) cached;</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        result = new EngineResource&lt;&gt;(cached, true /*isMemoryCacheable*/, true /*isRecyclable*/);</span><br><span class="line">    &#125;</span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第5行，<code>getEngineResourceFromCache()</code>，继续跟进来到第14行，<code>cache.remove()</code>上来就调用<code>remove()</code>方法，而这个<code>cache</code>是什么呢，我们在成员变量里面看到了</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">private final MemoryCache cache;</span><br></pre></td></tr></table></figure>
<p>而这个<code>MemoryCache</code>是个接口，并且这个<code>cache</code>对象是在<code>Engine</code>的构造方法中传入的，需要一层一层往上找，这里直接告诉大家结果是<code>LruResourceCache</code>对象。<code>LruResourceCache</code>是在Glide的构造里面初始化的，是默认值。接着我们来看一下他的<code>remove()</code>方法</p>
<h2 id="步骤7：LruResourceCache-remove"><a href="#步骤7：LruResourceCache-remove" class="headerlink" title="步骤7：LruResourceCache#remove()"></a>步骤7：LruResourceCache#remove()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public synchronized Y remove(@NonNull T key) &#123;</span><br><span class="line">    final Y value = cache.remove(key);</span><br><span class="line">    if (value != null) &#123;</span><br><span class="line">        currentSize -= getSize(value);</span><br><span class="line">    &#125;</span><br><span class="line">    return value;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个<code>remove()</code>方法实际上并不在<code>LruResourceCache</code>类中，这里贴一下它的继承结构</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LruResourceCache extends LruCache&lt;Key, Resource&lt;?&gt;&gt; implements MemoryCache</span><br></pre></td></tr></table></figure>
<p><code>remove()</code>方法是<code>MemoryCache</code>接口的抽象方法，<code>LruResourceCache</code>继承<code>LruCache</code>并指定泛型T为<code>Key</code>，所以上方<code>remove</code>方法中的T，实际上是Key，这样就对应上了。第2行，<code>cache.remove()</code>，这里的cache对象不用去找了，在<code>LruCache</code>类中被初始化成<code>LinkedHashMap</code>，这里将当前<code>key</code>对应的<code>Value</code>从<code>LruCache</code>中移除了，最终<code>return</code>了<code>Value</code>，也就是<code>Resource</code>对象，并且再回到步骤6的第7行和第8行，调用<code>acquire()</code>和<code>activate()</code>，也就是将<code>Resource</code>加入到了<code>ActiveResources</code>集合中</p>
<h2 id="步骤8：LruResourceCache与ActiveResources的关系"><a href="#步骤8：LruResourceCache与ActiveResources的关系" class="headerlink" title="步骤8：LruResourceCache与ActiveResources的关系"></a>步骤8：LruResourceCache与ActiveResources的关系</h2><p>我们在步骤2留了个疑问，当<code>acquired == 0</code>的时候回调<code>listener.onResourceReleased()</code>，是用来干嘛的，这里去看一下，首先这个<code>listener</code>也是调用<code>setResourceListener()</code>方法传入的，而调用<code>setResourceListener()</code>的地方是在步骤5第4行，也就是Engine对象，那来看看相关代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public void onResourceReleased(Key cacheKey, EngineResource&lt;?&gt; resource) &#123;</span><br><span class="line">    Util.assertMainThread();</span><br><span class="line">    activeResources.deactivate(cacheKey);</span><br><span class="line">    if (resource.isCacheable()) &#123;</span><br><span class="line">        cache.put(cacheKey, resource);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        resourceRecycler.recycle(resource);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第3行，当一个<code>Resource</code>的<code>acquired == 0</code>时，它会被<code>ActiveResources</code>移除，并且第5行，调用<code>cache.put()</code>，这个<code>cache</code>是<code>MemoryCache</code>，也就是<code>LruResourceCache</code>对象，所以他们的关系比较清晰了。接下来小结一下</p>
<h2 id="步骤9：内存缓存小结"><a href="#步骤9：内存缓存小结" class="headerlink" title="步骤9：内存缓存小结"></a>步骤9：内存缓存小结</h2><p>内存缓存分为两层</p>
<ol>
<li><code>ActiveResources</code>，当前正在使用的<code>Resouces</code>集合，使用优先级最高，为弱引用方式，来源于<code>Resource</code>加载成功的的回调，通过<code>acquired</code>变量控制在内存中的引用次数，当<code>acquired</code>为0的时候，会被放入<code>LruResourceCache</code>，并在<code>ActiveResources</code>中移除。</li>
<li><code>LruResourceCache</code>，最近最少使用的<code>Resouces</code>集合，优先级低于<code>ActiveResources</code>，强引用方式，当<code>ActiveResources</code>中有<code>Resource</code>被移除后，会被放入<code>LruResourceCache</code>，如果有<code>Resource</code>被使用了，那么会从<code>LruResourceCache</code>被移除，加入到<code>ActiveResources</code>中</li>
</ol>
<h1 id="磁盘缓存"><a href="#磁盘缓存" class="headerlink" title="磁盘缓存"></a>磁盘缓存</h1><p>说到磁盘缓存不得不说到<code>DiskCacheStrategy</code>，它代表着磁盘缓存策略，它在以前的版本有4个可选项，分别是</p>
<ol>
<li>DiskCacheStrategy.NONE： 表示不缓存任何内容</li>
<li>DiskCacheStrategy.SOURCE： 表示只缓存原始图片。</li>
<li>DiskCacheStrategy.RESULT： 表示只缓存转换过后的图片（默认选项）。</li>
<li>DiskCacheStrategy.ALL ： 表示既缓存原始图片，也缓存转换过后的图片。</li>
</ol>
<p>而现在的选项是</p>
<ol>
<li>DiskCacheStrategy.ALL</li>
<li>DiskCacheStrategy.NONE</li>
<li>DiskCacheStrategy.DATA：表示只缓存原始图片</li>
<li>DiskCacheStrategy.RESOURCE：表示只缓存转换过后的图片</li>
<li>DiskCacheStrategy.AUTOMATIC： 表示让Glide根据图片资源智能地选择使用哪一种缓存策略（默认选项）。</li>
</ol>
<p>因为我们并未指定<code>DiskCacheStrategy</code>，所以默认是<code>AUTOMATIC</code>，之前说到内存缓存有两层，磁盘缓存其实也是有两层的，也可以说有两种，分别是<strong>转换之后的图片缓存，和原始图片缓存</strong>。我们接着往下看，假设现在从内存中没有获取到结果，Glide会怎么做。</p>
<h2 id="步骤10：DecodeJob-run"><a href="#步骤10：DecodeJob-run" class="headerlink" title="步骤10：DecodeJob#run()"></a>步骤10：DecodeJob#run()</h2><p>为什么会从<code>DecodeJob#run()</code>方法开始呢，因为从步骤1得知，如果内存没有获取到结果，那么会继续走步骤1第76行，<code>engineJob.start(decodeJob);</code>这个方法我上一篇文章讲过，最终会开启<code>DecodeJob</code>线程。这里就不贴代码了，可以参考我上篇文章步骤17，18，19，最终来到<code>ResourceCacheGenerator#startNext()方法，ResourceCacheGenerator</code>类，我们在首次加载流程中分析过一次，上次是没有缓存，今天是有缓存，继续来看</p>
<h2 id="步骤11：ResourceCacheGenerator-startNext"><a href="#步骤11：ResourceCacheGenerator-startNext" class="headerlink" title="步骤11：ResourceCacheGenerator#startNext()"></a>步骤11：ResourceCacheGenerator#startNext()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">public boolean startNext() &#123;</span><br><span class="line">    List&lt;Key&gt; sourceIds = helper.getCacheKeys();</span><br><span class="line">    if (sourceIds.isEmpty()) &#123;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line">    List&lt;Class&lt;?&gt;&gt; resourceClasses = helper.getRegisteredResourceClasses();</span><br><span class="line">    if (resourceClasses.isEmpty()) &#123;</span><br><span class="line">        if (File.class.equals(helper.getTranscodeClass())) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    while (modelLoaders == null || !hasNextModelLoader()) &#123;</span><br><span class="line">        resourceClassIndex++;</span><br><span class="line">        if (resourceClassIndex &gt;= resourceClasses.size()) &#123;</span><br><span class="line">            sourceIdIndex++;</span><br><span class="line">            if (sourceIdIndex &gt;= sourceIds.size()) &#123;</span><br><span class="line">                return false;</span><br><span class="line">            &#125;</span><br><span class="line">            resourceClassIndex = 0;</span><br><span class="line">        &#125;</span><br><span class="line">        Key sourceId = sourceIds.get(sourceIdIndex);</span><br><span class="line">        Class&lt;?&gt; resourceClass = resourceClasses.get(resourceClassIndex);</span><br><span class="line">        Transformation&lt;?&gt; transformation = helper.getTransformation(resourceClass);</span><br><span class="line">        currentKey =</span><br><span class="line">                new ResourceCacheKey(// NOPMD AvoidInstantiatingObjectsInLoops</span><br><span class="line">                        helper.getArrayPool(),</span><br><span class="line">                        sourceId,</span><br><span class="line">                        helper.getSignature(),</span><br><span class="line">                        helper.getWidth(),</span><br><span class="line">                        helper.getHeight(),</span><br><span class="line">                        transformation,</span><br><span class="line">                        resourceClass,</span><br><span class="line">                        helper.getOptions());</span><br><span class="line">        cacheFile = helper.getDiskCache().get(currentKey);</span><br><span class="line">        if (cacheFile != null) &#123;</span><br><span class="line">            sourceKey = sourceId;</span><br><span class="line">            modelLoaders = helper.getModelLoaders(cacheFile);</span><br><span class="line">            modelLoaderIndex = 0;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    loadData = null;</span><br><span class="line">    boolean started = false;</span><br><span class="line">    while (!started &amp;&amp; hasNextModelLoader()) &#123;</span><br><span class="line">        ModelLoader&lt;File, ?&gt; modelLoader = modelLoaders.get(modelLoaderIndex++);</span><br><span class="line">        loadData = modelLoader.buildLoadData(cacheFile,</span><br><span class="line">                helper.getWidth(), helper.getHeight(), helper.getOptions());</span><br><span class="line">        if (loadData != null &amp;&amp; helper.hasLoadPath(loadData.fetcher.getDataClass())) &#123;</span><br><span class="line">            started = true;</span><br><span class="line">            loadData.fetcher.loadData(helper.getPriority(), this);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return started;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个方法，我们已经很熟悉了，其实就是对应着第一层磁盘缓存，也就是看有没有转换之后的图片缓存。直接来看第34行，<code>helper.getDiskCache().get()</code>，首先来看这个<code>DecodeHelper#getDiskCache()</code>方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">DiskCache getDiskCache() &#123;</span><br><span class="line">    return diskCacheProvider.getDiskCache();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>内部逻辑也很简单，就一行，<code>diskCacheProvider.getDiskCache()</code>，这个<code>diskCacheProvider</code>是初始化的时候传入的，直接给出答案是<code>LazyDiskCacheProvider</code>，接着来看<code>LazyDiskCacheProvider#getDiskCache()</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public DiskCache getDiskCache() &#123;</span><br><span class="line">    if (diskCache == null) &#123;</span><br><span class="line">        synchronized (this) &#123;</span><br><span class="line">            if (diskCache == null) &#123;</span><br><span class="line">                diskCache = factory.build();</span><br><span class="line">            &#125;</span><br><span class="line">            if (diskCache == null) &#123;</span><br><span class="line">                diskCache = new DiskCacheAdapter();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return diskCache;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第5行和第8行，这两行都是用来初始化的，而经过我实践证明，在第5行的时候已经初始化完成了。其中这个factory指的是<code>InternalCacheDiskCacheFactory</code>，接着来看下<code>InternalCacheDiskCacheFactory#build()</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public DiskCache build() &#123;</span><br><span class="line">    File cacheDir = cacheDirectoryGetter.getCacheDirectory();</span><br><span class="line">    if (cacheDir == null) &#123;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">    if (!cacheDir.mkdirs() &amp;&amp; (!cacheDir.exists() || !cacheDir.isDirectory())) &#123;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">    return DiskLruCacheWrapper.create(cacheDir, diskCacheSize);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第9行，<code>DiskLruCacheWrapper.create()</code>方法返回的是<code>DiskLruCacheWrapper</code>对象，所以最终<code>DiskCache</code>指向了<code>DiskLruCacheWrapper</code>对象。现在可以来看<code>DiskLruCacheWrapper#get()</code>方法</p>
<h2 id="步骤12：DiskLruCacheWrapper-get"><a href="#步骤12：DiskLruCacheWrapper-get" class="headerlink" title="步骤12：DiskLruCacheWrapper#get()"></a>步骤12：DiskLruCacheWrapper#get()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public File get(Key key) &#123;</span><br><span class="line">    String safeKey = safeKeyGenerator.getSafeKey(key);</span><br><span class="line">    if (Log.isLoggable(TAG, Log.VERBOSE)) &#123;</span><br><span class="line">        Log.v(TAG, &quot;Get: Obtained: &quot; + safeKey + &quot; for for Key: &quot; + key);</span><br><span class="line">    &#125;</span><br><span class="line">    File result = null;</span><br><span class="line">    try &#123;</span><br><span class="line">        final DiskLruCache.Value value = getDiskCache().get(safeKey);</span><br><span class="line">        if (value != null) &#123;</span><br><span class="line">            result = value.getFile(0);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; catch (IOException e) &#123;</span><br><span class="line">        if (Log.isLoggable(TAG, Log.WARN)) &#123;</span><br><span class="line">            Log.w(TAG, &quot;Unable to get from disk cache&quot;, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>步骤11第一段代码第34行<code>get()</code>方法，最终是调用<code>DiskLruCacheWrapper#get()</code>方法，获取<code>cacheFile</code>的值，其实这里不需要再往下走了，要看<code>get()</code>方法有没有值，只需要知道是否调用了<code>put()</code>方法或者<code>set()</code>方法，<code>DiskLruCacheWrapper</code>这个类中与<code>get()</code>方法对应的是<code>put()</code>方法。这里先不着急看<code>put()</code>方法的调用处，先给结果，在步骤11的循环中，<code>cacheFile</code>都是<code>null</code>，并没有获取到对应的缓存。既然<code>ResourceCacheGenerator</code>中没有获取到结果，那么只能到<code>SourceGenerator</code>中去看看了</p>
<h2 id="步骤13：DataCacheGenerator-startNext"><a href="#步骤13：DataCacheGenerator-startNext" class="headerlink" title="步骤13：DataCacheGenerator#startNext()"></a>步骤13：DataCacheGenerator#startNext()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">public boolean startNext() &#123;</span><br><span class="line">    while (modelLoaders == null || !hasNextModelLoader()) &#123;</span><br><span class="line">        sourceIdIndex++;</span><br><span class="line">        if (sourceIdIndex &gt;= cacheKeys.size()) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">        Key sourceId = cacheKeys.get(sourceIdIndex);</span><br><span class="line">        @SuppressWarnings(&quot;PMD.AvoidInstantiatingObjectsInLoops&quot;)</span><br><span class="line">        Key originalKey = new DataCacheKey(sourceId, helper.getSignature());</span><br><span class="line">        cacheFile = helper.getDiskCache().get(originalKey);</span><br><span class="line">        if (cacheFile != null) &#123;</span><br><span class="line">            this.sourceKey = sourceId;</span><br><span class="line">            modelLoaders = helper.getModelLoaders(cacheFile);</span><br><span class="line">            modelLoaderIndex = 0;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    loadData = null;</span><br><span class="line">    boolean started = false;</span><br><span class="line">    while (!started &amp;&amp; hasNextModelLoader()) &#123;</span><br><span class="line">        ModelLoader&lt;File, ?&gt; modelLoader = modelLoaders.get(modelLoaderIndex++);</span><br><span class="line">        loadData =</span><br><span class="line">                modelLoader.buildLoadData(cacheFile, helper.getWidth(), helper.getHeight(),</span><br><span class="line">                        helper.getOptions());</span><br><span class="line">        if (loadData != null &amp;&amp; helper.hasLoadPath(loadData.fetcher.getDataClass())) &#123;</span><br><span class="line">            started = true;</span><br><span class="line">            loadData.fetcher.loadData(helper.getPriority(), this);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return started;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同样是很熟悉的方法，如果有不明白为什么直接来到<code>DataCacheGenerator#startNext()</code>方法的朋友，还是请移步到第一篇文章去找寻答案啦。<code>DataCacheGenerator</code>这个类对应着原始图片缓存的获取，想必如果有缓存存在的话，这里一定是可以获取到数据的。</p>
<p>第10行，<code>helper.getDiskCache().get(originalKey)</code>这是和步骤11调用了一样的API，只不过传入的参数Key不一样了，变成了<code>DataCacheKey</code>对象。到这里想必不需要我说，大家也知道，这里肯定是拿得到结果。现在我们需要去了解的就是步骤12留下的问题<code>DiskLruCacheWrapper#put()</code>方法是什么时候调用的。</p>
<h2 id="步骤14：DiskLruCacheWrapper-put"><a href="#步骤14：DiskLruCacheWrapper-put" class="headerlink" title="步骤14：DiskLruCacheWrapper#put()"></a>步骤14：DiskLruCacheWrapper#put()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">public void put(Key key, Writer writer) &#123;</span><br><span class="line">    String safeKey = safeKeyGenerator.getSafeKey(key);</span><br><span class="line">    writeLocker.acquire(safeKey);</span><br><span class="line">    try &#123;</span><br><span class="line">        if (Log.isLoggable(TAG, Log.VERBOSE)) &#123;</span><br><span class="line">            Log.v(TAG, &quot;Put: Obtained: &quot; + safeKey + &quot; for for Key: &quot; + key);</span><br><span class="line">        &#125;</span><br><span class="line">        try &#123;</span><br><span class="line">            DiskLruCache diskCache = getDiskCache();</span><br><span class="line">            Value current = diskCache.get(safeKey);</span><br><span class="line">            if (current != null) &#123;</span><br><span class="line">                return;</span><br><span class="line">            &#125;</span><br><span class="line">            DiskLruCache.Editor editor = diskCache.edit(safeKey);</span><br><span class="line">            if (editor == null) &#123;</span><br><span class="line">                throw new IllegalStateException(&quot;Had two simultaneous puts for: &quot; + safeKey);</span><br><span class="line">            &#125;</span><br><span class="line">            try &#123;</span><br><span class="line">                File file = editor.getFile(0);</span><br><span class="line">                if (writer.write(file)) &#123;</span><br><span class="line">                    editor.commit();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; finally &#123;</span><br><span class="line">                editor.abortUnlessCommitted();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">            if (Log.isLoggable(TAG, Log.WARN)) &#123;</span><br><span class="line">                Log.w(TAG, &quot;Unable to put to disk cache&quot;, e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; finally &#123;</span><br><span class="line">        writeLocker.release(safeKey);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在看调用处之前，我们顺便来看下<code>put()</code>方法是不是与文件写入有关，第14行，得到一个<code>editor</code>，第19行，第20行，调用<code>writer.write()</code>方法，并且第21行调用<code>editor.commit()</code>，可以看出来，<code>put()</code>方法，就是用来写入缓存的， 虽然我们没有去深入缓存写入的逻辑，我们也没有必要去关注如何写入。接下来我们直接去找<code>put()</code>方法的调用处就可以了，总共有两处，首先来看第一处在<code>SourceGenerator</code>类中。</p>
<h2 id="步骤15：SourceGenerator-cacheData"><a href="#步骤15：SourceGenerator-cacheData" class="headerlink" title="步骤15：SourceGenerator#cacheData()"></a>步骤15：SourceGenerator#cacheData()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">private void cacheData(Object dataToCache) &#123;</span><br><span class="line">    long startTime = LogTime.getLogTime();</span><br><span class="line">    try &#123;</span><br><span class="line">        Encoder&lt;Object&gt; encoder = helper.getSourceEncoder(dataToCache);</span><br><span class="line">        DataCacheWriter&lt;Object&gt; writer =</span><br><span class="line">                new DataCacheWriter&lt;&gt;(encoder, dataToCache, helper.getOptions());</span><br><span class="line">        originalKey = new DataCacheKey(loadData.sourceKey, helper.getSignature());</span><br><span class="line">        helper.getDiskCache().put(originalKey, writer);</span><br><span class="line">        if (Log.isLoggable(TAG, Log.VERBOSE)) &#123;</span><br><span class="line">            Log.v(TAG, &quot;Finished encoding source to cache&quot;</span><br><span class="line">                    + &quot;, key: &quot; + originalKey</span><br><span class="line">                    + &quot;, data: &quot; + dataToCache</span><br><span class="line">                    + &quot;, encoder: &quot; + encoder</span><br><span class="line">                    + &quot;, duration: &quot; + LogTime.getElapsedMillis(startTime));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; finally &#123;</span><br><span class="line">        loadData.fetcher.cleanup();</span><br><span class="line">    &#125;</span><br><span class="line">    sourceCacheGenerator =</span><br><span class="line">            new DataCacheGenerator(Collections.singletonList(loadData.sourceKey), helper, this);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>目光放在第8行，我们看到了<code>put()</code>方法，而且传入的参数是<code>DataCacheKey</code>对象，表示最原始的数据。那么这个<code>cacheData()</code>方法是什么时候调用的呢。在上篇文章的步骤57就讲过了，也就是紧接着从网络加载完数据之后，立马就调用了<code>cacheData()</code>方法。到这里我们已经找到了原始数据缓存的地方。虽然在这个例子中转换之后的图片缓存，也就是<code>ResourceCache</code>是没有获取到结果的，但是我们可以尝试找一下在代码中是什么场景下才写入<code>ResourceCache</code></p>
<h2 id="步骤16：DecodeJob-DeferredEncodeManager-encode"><a href="#步骤16：DecodeJob-DeferredEncodeManager-encode" class="headerlink" title="步骤16：DecodeJob$DeferredEncodeManager#encode()"></a>步骤16：DecodeJob$DeferredEncodeManager#encode()</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">DeferredEncodeManager</span>&lt;<span class="title">Z</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Key key;</span><br><span class="line">    <span class="keyword">private</span> ResourceEncoder&lt;Z&gt; encoder;</span><br><span class="line">    <span class="keyword">private</span> LockedResource&lt;Z&gt; toEncode;</span><br><span class="line">    <span class="meta">@Synthetic</span></span><br><span class="line">    DeferredEncodeManager() &#123; &#125;</span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">    &lt;X&gt; <span class="function"><span class="keyword">void</span> <span class="title">init</span><span class="params">(Key key, ResourceEncoder&lt;X&gt; encoder, LockedResource&lt;X&gt; toEncode)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.key = key;</span><br><span class="line">        <span class="keyword">this</span>.encoder = (ResourceEncoder&lt;Z&gt;) encoder;</span><br><span class="line">        <span class="keyword">this</span>.toEncode = (LockedResource&lt;Z&gt;) toEncode;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">encode</span><span class="params">(DecodeJob.DiskCacheProvider diskCacheProvider, Options options)</span> </span>&#123;</span><br><span class="line">        GlideTrace.beginSection(<span class="string">"DecodeJob.encode"</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            diskCacheProvider.getDiskCache().put(key,</span><br><span class="line">                    <span class="keyword">new</span> DataCacheWriter&lt;&gt;(encoder, toEncode, options));</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            toEncode.unlock();</span><br><span class="line">            GlideTrace.endSection();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">hasResourceToEncode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    	<span class="keyword">return</span> toEncode != <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>步骤14中提到，<code>put()</code>方法有两处，第一处我们在步骤15看到了，这个步骤就是另一处，在第17行，我们看到了<code>put()</code>方法调用了，处于<code>DeferredEncodeManager</code>类中的<code>encode()</code>方法，这个<code>DeferredEncodeManager</code>类是<code>DecodeJob</code>中的内部类，我们我们主要看<code>DeferredEncodeManager#encode()</code>方法在哪里调用就好了</p>
<h2 id="步骤17：DecodeJob-notifyEncodeAndRelease"><a href="#步骤17：DecodeJob-notifyEncodeAndRelease" class="headerlink" title="步骤17：DecodeJob#notifyEncodeAndRelease()"></a>步骤17：DecodeJob#notifyEncodeAndRelease()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">private void notifyEncodeAndRelease(Resource&lt;R&gt; resource, DataSource dataSource) &#123;</span><br><span class="line">    if (resource instanceof Initializable) &#123;</span><br><span class="line">        ((Initializable) resource).initialize();</span><br><span class="line">    &#125;</span><br><span class="line">    Resource&lt;R&gt; result = resource;</span><br><span class="line">    LockedResource&lt;R&gt; lockedResource = null;</span><br><span class="line">    if (deferredEncodeManager.hasResourceToEncode()) &#123;</span><br><span class="line">        lockedResource = LockedResource.obtain(resource);</span><br><span class="line">        result = lockedResource;</span><br><span class="line">    &#125;</span><br><span class="line">    notifyComplete(result, dataSource);</span><br><span class="line">    stage = Stage.ENCODE;</span><br><span class="line">    try &#123;</span><br><span class="line">        if (deferredEncodeManager.hasResourceToEncode()) &#123;</span><br><span class="line">            deferredEncodeManager.encode(diskCacheProvider, options);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; finally &#123;</span><br><span class="line">        if (lockedResource != null) &#123;</span><br><span class="line">            lockedResource.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    onEncodeComplete();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>DecodeJob#notifyEncodeAndRelease()</code>这个方法也是见过的，在首次加载流程那篇文章的第62步骤，发生在<code>decodeFromRetrievedData()</code>方法之后，既然是我们认识的方法，那就不去多说了，首先在第14行看到有个判断条件，<code>deferredEncodeManager.hasResourceToEncode()</code>，再次回到步骤16第25行，看到了<code>hasResourceToEncode()</code>方法，判断依据很简单<code>toEncode != null</code>，只要<code>toEncode</code>不为<code>null</code>，就可以执行<code>encode()</code>方法，这个<code>toEncode</code>是在<code>DeferredEncodeManager#init()</code>方法中初始化的，接下来看一下<code>DeferredEncodeManager#init()</code>方法的调用处</p>
<h2 id="步骤18：DecodeJob-onResourceDecoded"><a href="#步骤18：DecodeJob-onResourceDecoded" class="headerlink" title="步骤18：DecodeJob#onResourceDecoded()"></a>步骤18：DecodeJob#onResourceDecoded()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">&lt;Z&gt; Resource&lt;Z&gt; onResourceDecoded(DataSource dataSource,</span><br><span class="line">                                  @NonNull Resource&lt;Z&gt; decoded) &#123;</span><br><span class="line">    @SuppressWarnings(&quot;unchecked&quot;)</span><br><span class="line">    Class&lt;Z&gt; resourceSubClass = (Class&lt;Z&gt;) decoded.get().getClass();</span><br><span class="line">    Transformation&lt;Z&gt; appliedTransformation = null;</span><br><span class="line">    Resource&lt;Z&gt; transformed = decoded;</span><br><span class="line">    if (dataSource != DataSource.RESOURCE_DISK_CACHE) &#123;</span><br><span class="line">        appliedTransformation = decodeHelper.getTransformation(resourceSubClass);</span><br><span class="line">        transformed = appliedTransformation.transform(glideContext, decoded, width, height);</span><br><span class="line">    &#125;</span><br><span class="line">    if (!decoded.equals(transformed)) &#123;</span><br><span class="line">        decoded.recycle();</span><br><span class="line">    &#125;</span><br><span class="line">    final EncodeStrategy encodeStrategy;</span><br><span class="line">    final ResourceEncoder&lt;Z&gt; encoder;</span><br><span class="line">    if (decodeHelper.isResourceEncoderAvailable(transformed)) &#123;</span><br><span class="line">        encoder = decodeHelper.getResultEncoder(transformed);</span><br><span class="line">        encodeStrategy = encoder.getEncodeStrategy(options);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        encoder = null;</span><br><span class="line">        encodeStrategy = EncodeStrategy.NONE;</span><br><span class="line">    &#125;</span><br><span class="line">    Resource&lt;Z&gt; result = transformed;</span><br><span class="line">    boolean isFromAlternateCacheKey = !decodeHelper.isSourceKey(currentSourceKey);</span><br><span class="line">    if (diskCacheStrategy.isResourceCacheable(isFromAlternateCacheKey, dataSource,</span><br><span class="line">            encodeStrategy)) &#123;</span><br><span class="line">        if (encoder == null) &#123;</span><br><span class="line">            throw new Registry.NoResultEncoderAvailableException(transformed.get().getClass());</span><br><span class="line">        &#125;</span><br><span class="line">        final Key key;</span><br><span class="line">        switch (encodeStrategy) &#123;</span><br><span class="line">            case SOURCE:</span><br><span class="line">                key = new DataCacheKey(currentSourceKey, signature);</span><br><span class="line">                break;</span><br><span class="line">            case TRANSFORMED:</span><br><span class="line">                key =</span><br><span class="line">                        new ResourceCacheKey(</span><br><span class="line">                                decodeHelper.getArrayPool(),</span><br><span class="line">                                currentSourceKey,</span><br><span class="line">                                signature,</span><br><span class="line">                                width,</span><br><span class="line">                                height,</span><br><span class="line">                                appliedTransformation,</span><br><span class="line">                                resourceSubClass,</span><br><span class="line">                                options);</span><br><span class="line">                break;</span><br><span class="line">            default:</span><br><span class="line">                throw new IllegalArgumentException(&quot;Unknown strategy: &quot; + encodeStrategy);</span><br><span class="line">        &#125;</span><br><span class="line">        LockedResource&lt;Z&gt; lockedResult = LockedResource.obtain(transformed);</span><br><span class="line">        deferredEncodeManager.init(key, encoder, lockedResult);</span><br><span class="line">        result = lockedResult;</span><br><span class="line">    &#125;</span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在第51行，<code>deferredEncodeManager.init(key, encoder, lockedResult);</code>找到了<code>DeferredEncodeManager#init()</code>的调用处，也仅有这一处，只需要<code>lockedResult</code>不是null就可以了。但是不急这里不是关键，先看第25行，有个判断条件，只有条件成立我们才有可能执行<code>init()</code>方法，那我们来看一下这个判断条件<code>diskCacheStrategy.isResourceCacheable()</code>，这个<code>diskCacheStrategy</code>是<code>AUTOMATIC</code>不用多说了</p>
<h2 id="步骤19：AUTOMATIC-isResourceCacheable"><a href="#步骤19：AUTOMATIC-isResourceCacheable" class="headerlink" title="步骤19：AUTOMATIC#isResourceCacheable()"></a>步骤19：AUTOMATIC#isResourceCacheable()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public boolean isResourceCacheable(boolean isFromAlternateCacheKey, DataSource dataSource,EncodeStrategy encodeStrategy) &#123;</span><br><span class="line">    return ((isFromAlternateCacheKey &amp;&amp; dataSource == DataSource.DATA_DISK_CACHE)</span><br><span class="line">            || dataSource == DataSource.LOCAL)</span><br><span class="line">            &amp;&amp; encodeStrategy == EncodeStrategy.TRANSFORMED;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>来看一下这个判断条件，<code>(isFromAlternateCacheKey &amp;&amp; dataSource == DataSource.DATA_DISK_CACHE)</code>第一组，与<code>dataSource == DataSource.LOCAL</code>是二选一，另一个<code>encodeStrategy == EncodeStrategy.TRANSFORMED</code>条件是必须要满足，在我们此次的分析中，传入的这三个参数分别是什么呢？</p>
<ol>
<li>isFromAlternateCacheKey = false;</li>
<li>dataSource = DataSource.DATA_DISK_CACHE;</li>
<li>encodeStrategy = EncodeStrategy.TRANSFORMED;</li>
</ol>
<p>最终的判断结果是false，导致没有进行<code>ResourceCache</code>，只因为<code>isFromAlternateCacheKey</code>这个条件没有满足，而这个条件是由步骤18第24行<code>!decodeHelper.isSourceKey(currentSourceKey)</code>产生的，直接由<code>currentSourceKey</code>决定，而这个<code>decodeHelper.isSourceKey()</code>方法，看名字就知道，用来判断传入的key是不是<code>SourceKey</code>，下面来看一下<code>currentSourceKey</code>赋值的地方。</p>
<h2 id="步骤20：DecodeJob-onDataFetcherReady"><a href="#步骤20：DecodeJob-onDataFetcherReady" class="headerlink" title="步骤20：DecodeJob#onDataFetcherReady()"></a>步骤20：DecodeJob#onDataFetcherReady()</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public void onDataFetcherReady(Key sourceKey, Object data, DataFetcher&lt;?&gt; fetcher,</span><br><span class="line">                               DataSource dataSource, Key attemptedKey) &#123;</span><br><span class="line">    this.currentSourceKey = sourceKey;</span><br><span class="line">    this.currentData = data;</span><br><span class="line">    this.currentFetcher = fetcher;</span><br><span class="line">    this.currentDataSource = dataSource;</span><br><span class="line">    this.currentAttemptingKey = attemptedKey;</span><br><span class="line">    if (Thread.currentThread() != currentThread) &#123;</span><br><span class="line">        runReason = DecodeJob.RunReason.DECODE_DATA;</span><br><span class="line">        callback.reschedule(this);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        GlideTrace.beginSection(&quot;DecodeJob.decodeFromRetrievedData&quot;);</span><br><span class="line">        try &#123;</span><br><span class="line">            decodeFromRetrievedData();</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            GlideTrace.endSection();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第3行，我们找到了<code>currentSourceKey</code>赋值的地方，而这个<code>onDataFetcherReady()</code>方法也是我们熟悉的方法，在上篇文章步骤59出现过，调用时机为<code>Resource</code>加载成功的回调，继续跟踪这个方法的调用处的话，会发现有4个调用处</p>
<ol>
<li><p>DataCacheGenerator</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public void onDataReady(Object data) &#123;</span><br><span class="line">    cb.onDataFetcherReady(sourceKey, data, loadData.fetcher, DataSource.DATA_DISK_CACHE, sourceKey);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>ResourceCacheGenerator</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public void onDataReady(Object data) &#123;</span><br><span class="line">    cb.onDataFetcherReady(sourceKey, data, loadData.fetcher, DataSource.RESOURCE_DISK_CACHE,</span><br><span class="line">            currentKey);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>SourceGenerator</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public void onDataReady(Object data) &#123;</span><br><span class="line">    DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();</span><br><span class="line">    if (data != null &amp;&amp; diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource())) &#123;</span><br><span class="line">        dataToCache = data;</span><br><span class="line">        cb.reschedule();</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,</span><br><span class="line">                loadData.fetcher.getDataSource(), originalKey);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>SourceGenerator</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public void onDataFetcherReady(Key sourceKey, Object data, DataFetcher&lt;?&gt; fetcher,</span><br><span class="line">                               DataSource dataSource, Key attemptedKey) &#123;</span><br><span class="line">    cb.onDataFetcherReady(sourceKey, data, fetcher, loadData.fetcher.getDataSource(), sourceKey);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这几个回调方法，返回的第4个参数，<code>dataSource</code>其实也是和步骤19的第二个判断条件相关，和sourceKey一样，也是在这个方法中传入的。现在凭空看这些个回调方法，貌似是没有什么收获的，但我们首先可以排除第二个回调，也就是<code>ResourceCacheGenerator</code>的回调，因为他的<code>dataSource</code>是<code>RESOURCE_DISK_CACHE</code>，并不符合步骤19的条件，第3个和第4个也可以排除了，因为3和4都是从网络上下载原始数据，这一步我们已经执行过了，最后也没有缓存<code>ResourceCache</code>。那就把目光放在<code>DataCacheGenerator</code>上吧，这个<code>DataCacheGenerator#onDataReady()</code>方法就是我们刚刚分析过的原图缓存回调，然而很遗憾，<code>DataCacheGenerator#onDataReady()</code>中的<code>sourceKey</code>是<code>originalKey</code>（可以理解为URL），也就是说，从原图缓存拿到的结果，不会被缓存到<code>ResourceCache</code>中。</p>
</li>
</ol>
<h2 id="步骤21：AUTOMATIC缓存机制"><a href="#步骤21：AUTOMATIC缓存机制" class="headerlink" title="步骤21：AUTOMATIC缓存机制"></a>步骤21：AUTOMATIC缓存机制</h2><p>这里给一下解释，当我们使用默认的缓存策略AUTOMATIC时，内部会是什么样的逻辑，这里直接引用Glide官方中文翻译</p>
<blockquote>
<p>默认的策略叫做 AUTOMATIC ，它会尝试对本地和远程图片使用最佳的策略。当你加载远程数据（比如，从URL下载）时，AUTOMATIC 策略仅会存储未被你的加载过程修改过(比如，变换，裁剪–译者注)的原始数据，因为下载远程数据相比调整磁盘上已经存在的数据要昂贵得多。对于本地数据，AUTOMATIC 策略则会仅存储变换过的缩略图，因为即使你需要再次生成另一个尺寸或类型的图片，取回原始数据也很容易。</p>
</blockquote>
<p>从这段文字得知，当我们采用网络请求获得结果时，只会对原图进行缓存，当加载本地数据（手机上存储的图片）的时候，才会缓存变换过后的<code>ResourceCache</code>。所以，这里已经得到结果了，默认的磁盘策略并不会为我们缓存转换后的图片的。不过我们之前的分析也没有白费，通过分析AUTOMATIC，也能帮助我们了解其他缓存策略是如何工作的。</p>
<h2 id="步骤22：加载本地图片"><a href="#步骤22：加载本地图片" class="headerlink" title="步骤22：加载本地图片"></a>步骤22：加载本地图片</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">File file = new File(Environment.getExternalStorageDirectory(), &quot;xxx.jpg&quot;);</span><br><span class="line">Glide.with(MainActivity.this).load(file).into(imageView);</span><br></pre></td></tr></table></figure>
<p>当我们首次调用上方代码，缓存策略同样是AUTOMATIC，最终在步骤19中传入的参数就会是</p>
<ol>
<li>isFromAlternateCacheKey = false;</li>
<li>dataSource = DataSource.LOCAL;</li>
<li>encodeStrategy = EncodeStrategy.TRANSFORMED;</li>
</ol>
<p>第二个参数变成了DataSource.LOCAL，从而满足了步骤19的条件，进而进行ResourceCache的缓存</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Glide/" rel="tag"># Glide</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        
          <div class="wp_rating">
            <div id="wpac-rating"></div>
          </div>
        

        

        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/11/Glide(1)-基于Glide4.8源码的首次加载流程/" rel="next" title="Glide(1)-基于Glide4.8源码的首次加载流程">
                <i class="fa fa-chevron-left"></i> Glide(1)-基于Glide4.8源码的首次加载流程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">lt19931203</p>
              <p class="site-description motion-element" itemprop="description">技术道路，勇于向前</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#序言"><span class="nav-number">1.</span> <span class="nav-text">序言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#简介"><span class="nav-number">2.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#内存缓存"><span class="nav-number">3.</span> <span class="nav-text">内存缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤1：Engine-load"><span class="nav-number">3.1.</span> <span class="nav-text">步骤1：Engine#load()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤2：Engine-loadFromActiveResources"><span class="nav-number">3.2.</span> <span class="nav-text">步骤2：Engine#loadFromActiveResources()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤3：SingleRequest-onResourceReady"><span class="nav-number">3.3.</span> <span class="nav-text">步骤3：SingleRequest#onResourceReady()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤4：ActiveResources缓存的来源"><span class="nav-number">3.4.</span> <span class="nav-text">步骤4：ActiveResources缓存的来源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤5：Engine-onEngineJobComplete"><span class="nav-number">3.5.</span> <span class="nav-text">步骤5：Engine#onEngineJobComplete()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤6：Engine-loadFromCache"><span class="nav-number">3.6.</span> <span class="nav-text">步骤6：Engine#loadFromCache()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤7：LruResourceCache-remove"><span class="nav-number">3.7.</span> <span class="nav-text">步骤7：LruResourceCache#remove()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤8：LruResourceCache与ActiveResources的关系"><span class="nav-number">3.8.</span> <span class="nav-text">步骤8：LruResourceCache与ActiveResources的关系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤9：内存缓存小结"><span class="nav-number">3.9.</span> <span class="nav-text">步骤9：内存缓存小结</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#磁盘缓存"><span class="nav-number">4.</span> <span class="nav-text">磁盘缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤10：DecodeJob-run"><span class="nav-number">4.1.</span> <span class="nav-text">步骤10：DecodeJob#run()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤11：ResourceCacheGenerator-startNext"><span class="nav-number">4.2.</span> <span class="nav-text">步骤11：ResourceCacheGenerator#startNext()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤12：DiskLruCacheWrapper-get"><span class="nav-number">4.3.</span> <span class="nav-text">步骤12：DiskLruCacheWrapper#get()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤13：DataCacheGenerator-startNext"><span class="nav-number">4.4.</span> <span class="nav-text">步骤13：DataCacheGenerator#startNext()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤14：DiskLruCacheWrapper-put"><span class="nav-number">4.5.</span> <span class="nav-text">步骤14：DiskLruCacheWrapper#put()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤15：SourceGenerator-cacheData"><span class="nav-number">4.6.</span> <span class="nav-text">步骤15：SourceGenerator#cacheData()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤16：DecodeJob-DeferredEncodeManager-encode"><span class="nav-number">4.7.</span> <span class="nav-text">步骤16：DecodeJob$DeferredEncodeManager#encode()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤17：DecodeJob-notifyEncodeAndRelease"><span class="nav-number">4.8.</span> <span class="nav-text">步骤17：DecodeJob#notifyEncodeAndRelease()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤18：DecodeJob-onResourceDecoded"><span class="nav-number">4.9.</span> <span class="nav-text">步骤18：DecodeJob#onResourceDecoded()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤19：AUTOMATIC-isResourceCacheable"><span class="nav-number">4.10.</span> <span class="nav-text">步骤19：AUTOMATIC#isResourceCacheable()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤20：DecodeJob-onDataFetcherReady"><span class="nav-number">4.11.</span> <span class="nav-text">步骤20：DecodeJob#onDataFetcherReady()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤21：AUTOMATIC缓存机制"><span class="nav-number">4.12.</span> <span class="nav-text">步骤21：AUTOMATIC缓存机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤22：加载本地图片"><span class="nav-number">4.13.</span> <span class="nav-text">步骤22：加载本地图片</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lt19931203</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  
  <script type="text/javascript">
  wpac_init = window.wpac_init || [];
  wpac_init.push({widget: 'Rating', id: ,
    el: 'wpac-rating',
    color: 'fc6423'
  });
  (function() {
    if ('WIDGETPACK_LOADED' in window) return;
    WIDGETPACK_LOADED = true;
    var mc = document.createElement('script');
    mc.type = 'text/javascript';
    mc.async = true;
    mc.src = '//embed.widgetpack.com/widget.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
  })();
  </script>


  

  

  

</body>
</html>
